/**
 * Copyright (c) 2017-2018, zengjintao (1913188966@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfast.framework.web.resolver;

import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletContext;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import com.jfast.framework.exception.ResolverException;

public class VelocityResolver extends ViewResolver {
	
	private static final String contentType = "text/html; charset=" + getEncoding();
	private static final Properties properties = new Properties();
	
	private boolean isNotInit = true;
	
	static void init(ServletContext servletContext){
		String webPath = servletContext.getRealPath("/");
		if (webPath == null) {
			try {
				webPath = servletContext.getResource("/").getPath();
			} catch (java.net.MalformedURLException e) {
				e.printStackTrace();
			}
		}
		properties.setProperty(Velocity.ENCODING_DEFAULT, getEncoding());
		properties.setProperty(Velocity.INPUT_ENCODING, getEncoding()); 
		properties.setProperty(Velocity.OUTPUT_ENCODING, getEncoding());
		properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, webPath);
	}
	
	public String getContentType() {
		return contentType;
	}

	public Properties getProperties() {
		return properties;
	}

	
	@Override
	public void render() {
		
		if(isNotInit){
			Velocity.init(properties);
			isNotInit = false;
		}
		
		PrintWriter writer = null;
		String view = null;
		try {
			VelocityContext context = new VelocityContext();
			for (Enumeration<String> attrs = request.getAttributeNames(); attrs.hasMoreElements();) {
				String attrName = attrs.nextElement();
				context.put(attrName, request.getAttribute(attrName));
			}
		    view = config.getBaseViewPath() + (String)returnValue + config.getSuffix();
			Template template = Velocity.getTemplate(view);
			response.setContentType(getContentType()); 
            writer = response.getWriter();	
            template.merge(context, writer);
		} catch (Exception e) {
			throw new ResolverException("Example : error : cannot find template " + view, e);
		}
	}
}
